package cn.cold.face;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.stream.FileImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class MinshApi {
	private static final Logger log = LoggerFactory.getLogger(MinshApi.class);
	private static String key = "E0CE55CF";
	private static String merchantId = "10001";
	private static String account = "hzhu";
	private static RestTemplate RT;
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static {
		SimpleClientHttpRequestFactory reques = new SimpleClientHttpRequestFactory();
		reques.setReadTimeout(30000);
		reques.setConnectTimeout(30000);
		RT = new RestTemplate(reques);
	}

	private static SimpleIDSearchResponse Face1v1(String databaseImageContent, String queryImageContent, String address) {
		Map<String, String> req = new HashMap<String, String>();
		req.put("databaseImageContent", Base64.encode(Image2byte(databaseImageContent)));
		req.put("databaseImageType", "1");
		req.put("queryImageContent", Base64.encode(Image2byte(queryImageContent)));
		req.put("queryImageType", "303");
		req.put("trueNegativeRate", "99.99");

		String strRequest = getEncrypt(req);

		HttpHeaders headers = new HttpHeaders();
		headers.add("MerchantID", merchantId);
		headers.add("Account", getEncrypt(account));

		long timeStamp = System.currentTimeMillis();

		headers.add("TimeStamp", getEncrypt(String.valueOf(timeStamp)));
		HttpEntity<String> formEntity = new HttpEntity<String>(strRequest, headers);
		ResponseEntity<String> result = null;
		try {
			long start = System.currentTimeMillis();
			result = RT.exchange(address, HttpMethod.POST, formEntity,
					String.class, new Object[0]);
			long end = System.currentTimeMillis();
			log.info("请求开始时间: {}, 请求结束时间: {}, 总耗时: {}.", SDF.format(start), SDF.format(end), (end-start));
		} catch (Exception e) {
			System.out.println("请求错误："+e.getMessage());
		}

		String strResponse = null;
		try {
			strResponse = (String) result.getBody();
		} catch (Exception e) {
			System.out.println("获取返回Body出错");
		}
		SimpleIDSearchResponse simpl = null;
		strResponse = getDecrypted(strResponse);
		try {
			simpl = (SimpleIDSearchResponse) new ObjectMapper().readValue(strResponse, SimpleIDSearchResponse.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return simpl;
	}

	public static byte[] Image2byte(String path) {
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		} catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
		} catch (IOException ex1) {
			ex1.printStackTrace();
		}
		return data;
	}

	private static String getEncrypt(Map<String, String> req) {
		String reqJson = null;
		try {
			reqJson = new ObjectMapper().writeValueAsString(req);

			DES des = new DES(key);
			reqJson = des.encrypt(reqJson);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reqJson;
	}

	private static String getEncrypt(String reqData) {
		try {
			DES des = new DES(key);
			reqData = des.encrypt(reqData);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reqData;
	}

	private static String getDecrypted(String encryptedData) {
		String data = null;
		try {
			DES des = new DES(key);
			data = des.decrypt(encryptedData);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	public static SimpleIDSearchResponse OneToOne(String IdImg, String people,String address) throws RestClientException, Exception {
		return Face1v1(IdImg, people, address);
	}

}
